package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
)

func sendFile(fileName, url string) (string, error) {
	file, err := os.Open(fileName)
	if err != nil {
		log.Println(err)
		return "", err
	}
	fmt.Println(fileName, file)
	defer func() {
		if err = file.Close(); err != nil {
			log.Println(err)
			return
		}
	}()
	msg := &bytes.Buffer{}
	writer := multipart.NewWriter(msg)
	formFile, err := writer.CreateFormFile("uploader", fileName)
	_, err = io.Copy(formFile, file)
	if err != nil {
		log.Println(err)
		return "", nil
	}
	if err = writer.Close(); err != nil {
		log.Println(err)
		return "", nil
	}
	// 创建http post请求，这个还是第一次写
	request, err := http.NewRequest("POST", url, msg)
	if err != nil {
		log.Println(err)
		return "", nil
	}
	request.Header.Set("Content-Type", writer.FormDataContentType()) // 这里的writer是一个符合http发送请求的编码格式，这样适配一些
	client := http.Client{}
	response, err := client.Do(request)
	if err != nil {
		log.Println(err)
		return "", nil
	}
	defer func() {
		if err = response.Body.Close(); err != nil {
			log.Println(err)
			return
		}
	}()
	// 提取response中的内容
	if response.StatusCode != 200 {
		log.Println("error on post msg, statusCode : ", response.StatusCode)
	}
	readFromResponse, err := io.ReadAll(response.Body)
	if err != nil {
		log.Println(err)
		return "", nil
	}
	//fmt.Println("msg1: ", string(readFromResponse))
	return string(readFromResponse), nil
}
